﻿using System.Text;
using System.Windows;
using System.Windows.Media;
using WpfApp1.Models;
using WpfApp1.Services;
using WpfApp1.Utils;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly DatabaseService _databaseService;
        private readonly DataProcessingService _dataProcessingService;

        public MainWindow()
        {
            InitializeComponent();
            _databaseService = new DatabaseService();
            _dataProcessingService = new DataProcessingService();
        }

        /// <summary>
        /// 读取数据按钮点击事件
        /// </summary>
        private async void BtnReadTID_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 禁用按钮，防止重复点击
                btnReadTID.IsEnabled = false;

                // 更新状态
                UpdateStatus("正在连接...", Colors.Orange);

                // 获取连接参数
                string serverIp = txtServerIp.Text.Trim();
                if (!int.TryParse(txtServerPort.Text.Trim(), out int serverPort))
                {
                    UpdateStatus("端口号格式错误", Colors.Red);
                    return;
                }

                string command = "sMN TAreadTagData 0 2 0 6 32";
                if (string.IsNullOrEmpty(command))
                {
                    UpdateStatus("请选择命令", Colors.Red);
                    return;
                }

                // 执行TCP连接和数据读取
                await ReadTcpDataAsync(serverIp, serverPort, command, CommandType.ReadTid);
            }
            catch (Exception ex)
            {
                UpdateStatus($"错误: {ex.Message}", Colors.Red);
                AppendResult($"发生错误: {ex.Message}");
            }
            finally
            {
                // 恢复按钮状态
                btnReadTID.IsEnabled = true;
            }
        }

        /// <summary>
        /// 异步读取TCP数据
        /// </summary>
        private async Task ReadTcpDataAsync(
            string serverIp,
            int serverPort,
            string command,
            CommandType commandType
        )
        {
            try
            {
                // 创建TCP客户端并发送数据
                using (var tcpClient = new TcpClientWrapper())
                {
                    // 连接到服务器
                    await tcpClient.ConnectAsync(serverIp, serverPort);
                    //UpdateStatus($"已连接到 {serverIp}:{serverPort}", Colors.Green);
                    //AppendResult($"已连接到 {serverIp}:{serverPort}");

                    // 发送数据
                    byte[] dataToSend = TcpClientWrapper.CreateCmdData(command);
                    await tcpClient.SendAsync(dataToSend);
                    //AppendResult($"已发送命令: {command}");

                    // 接收响应
                    byte[] response = await tcpClient.ReceiveAsync();
                    string responseText = Encoding.ASCII.GetString(response);
                    //AppendResult($"收到响应: {responseText}");

                    if (response.Length <= 23)
                    {
                        UpdateStatus("未获取到有效值", Colors.Red);
                        AppendResult("响应数据长度不足，未获取到有效值");

                        // 保存无效记录到数据库
                        var invalidRecord = new TcpDataRecord
                        {
                            ServerIp = serverIp,
                            ServerPort = serverPort,
                            Command = command,
                            ExtractedData = "未获取到有效值",
                            RawResponse = BitConverter.ToString(response),
                            CreatedAt = DateTime.Now,
                            IsValid = false,
                        };

                        int recordId = await _databaseService.SaveTcpDataRecordAsync(invalidRecord);
                        AppendResult($"无效记录已保存到数据库，ID: {recordId}");
                    }
                    else
                    {
                        // 处理有效数据
                        var record = _dataProcessingService.ProcessValidData(
                            response,
                            serverIp,
                            serverPort,
                            command
                        );

                        if (record.IsValid)
                        {
                            UpdateStatus("数据读取成功", Colors.Green);
                            AppendResult($"提取的数据: {record.ExtractedData}");

                            if (commandType == CommandType.ReadTid)
                            {
                                txtTID.Text = record.ExtractedData;
                            }

                            if (commandType == CommandType.ReadEpc)
                            {
                                txtEPC.Text = HexUtil.HexToString(record.ExtractedData);
                                //AppendResult($"ASCII: {HexUtil.HexToString(record.ExtractedData)}");
                            }

                        }
                        else
                        {
                            UpdateStatus("数据处理失败", Colors.Red);
                            AppendResult($"数据处理失败: {record.ExtractedData}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"连接失败: {ex.Message}", Colors.Red);
                AppendResult($"连接失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 更新状态显示
        /// </summary>
        private void UpdateStatus(string message, Color color)
        {
            txtStatus.Text = message;
            txtStatus.Foreground = new SolidColorBrush(color);
        }

        /// <summary>
        /// 追加结果显示
        /// </summary>
        private void AppendResult(string message)
        {
            txtResult.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}{Environment.NewLine}");
            txtResult.ScrollToEnd();
        }


        private async void btnWriteEPC_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtContent.Text))
                {
                    MessageBox.Show("写入内容不能为空");
                    return;
                }
                if (txtContent.Text?.Length > 16)
                {
                    MessageBox.Show("写入内容长度不能大于16");
                    return;
                }

                // 禁用按钮，防止重复点击
                btnWriteEPC.IsEnabled = false;

                // 更新状态
                UpdateStatus("正在连接...", Colors.Orange);

                // 获取连接参数
                string serverIp = txtServerIp.Text.Trim();
                if (!int.TryParse(txtServerPort.Text.Trim(), out int serverPort))
                {
                    UpdateStatus("端口号格式错误", Colors.Red);
                    return;
                }

                var message = txtContent.Text;
                while (message.Length < 16)
                {
                    message += "*";
                }

                var bytes = Encoding.ASCII.GetBytes(message);

                // 2. 转为十六进制字符串（带连字符）
                string hexWithDash = BitConverter.ToString(bytes);

                // 3. 去掉连字符，拼接成连续字符串
                string hex = hexWithDash.Replace("-", "");

                string command =
                    $"sMN TAadvWriteTagData 2 0 +24 {txtTID.Text} 1 2 8 32 +32 {hex} 1";
                if (string.IsNullOrEmpty(command))
                {
                    UpdateStatus("请输入命令", Colors.Red);
                    return;
                }

                // 执行TCP连接和数据读取
                await ReadTcpDataAsync(serverIp, serverPort, command,CommandType.WriteData);
            }
            catch (Exception ex)
            {
                UpdateStatus($"错误: {ex.Message}", Colors.Red);
                AppendResult($"发生错误: {ex.Message}");
            }
            finally
            {
                // 恢复按钮状态
                btnWriteEPC.IsEnabled = true;
            }
        }

        private async void btnReadEPC_Click(object sender, RoutedEventArgs e) {
            try
            {
                // 禁用按钮，防止重复点击
                btnReadEPC.IsEnabled = false;

                // 更新状态
                UpdateStatus("正在连接...", Colors.Orange);

                // 获取连接参数
                string serverIp = txtServerIp.Text.Trim();
                if (!int.TryParse(txtServerPort.Text.Trim(), out int serverPort))
                {
                    UpdateStatus("端口号格式错误", Colors.Red);
                    return;
                }

                string command = "sMN TAreadTagData 0 1 2 8 32";
                if (string.IsNullOrEmpty(command))
                {
                    UpdateStatus("请选择命令", Colors.Red);
                    return;
                }

                // 执行TCP连接和数据读取
                await ReadTcpDataAsync(serverIp, serverPort, command, CommandType.ReadEpc);
            }
            catch (Exception ex)
            {
                UpdateStatus($"错误: {ex.Message}", Colors.Red);
                AppendResult($"发生错误: {ex.Message}");
            }
            finally
            {
                // 恢复按钮状态
                btnReadEPC.IsEnabled = true;
            }

        }
    }

    public enum CommandType
    {
        ReadTid,
        WriteData,
        ReadEpc
    }
}
